package com.ckr.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckr.common.dto.LoginDto;
import com.ckr.common.lang.Result;
import com.ckr.entity.User;
import com.ckr.service.UserService;
import com.ckr.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * 账户（登录，登出）控制器
 *
 * @author Shadowckr
 * @create 2022-02-08 11:19
 */

@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserService userService;

    /*
    登录只需要接受用户的账号和密码，然后把用户的id生成jwt，返回给前端。
    为了后续jwt的延期，我们把jwt放在了header上。
    默认账号和密码：markerhub / 111111
     */

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        Assert.notNull(user, "用户不存在！");
        // 因为数据库中密码用了md5加密，所以这里也要将前端传递过来的密码进行md5加密判断
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("密码不正确！");
        }
//        if (user.getStatus() == 0) {
//            return Result.fail("用户已被禁用！");
//        }
        String jwt = jwtUtils.generateToken(user.getId(), user.getUsername());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");
        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()
        );
    }

    // 需要认证权限才能退出登录
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        // 退出登录
        SecurityUtils.getSubject().logout();
        return Result.success("用户登出成功！");
    }

}
